#!/bin/bash
#
# Downloads and imports public keys for subscription verification, etc.
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 19 November 2013
#
#   Copyright 2011-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## p_cmd_import_key_help
##
## Echoes help information for the import_key command. Returns 0.
##
function p_cmd_import_key_help() {
	cat << EOF
Usage: pulley import_key [options] <key URL>

Downloads and imports a public key for use in validating subscription
signatures or other purposes. The <key URL> may be the path to an existing
public key present on the local filesystem, or it may be a URL from which
to download the key.

Available options are:

--section <section>
  Imports the public key into the specified <section> of the key store. If
  this option is not given, the subscription section is used by default.

--security <provider>
  Use the specified security <provider>. By default, the provider specified
  by the Pulley subscription will be used.

EOF
	return 0
}


## p_cmd_import_key_summary
##
## Echoes summary information for the import_key command. Returns 0.
##
function p_cmd_import_key_summary() {
	echo "Imports a public key from a file or URL"
	return 0
}


## p_cmd_import_key [options] <key URL>
##
## Implements the import_key command, downloading the key from the <key URL>
## and importing.
##
## [options] are:
##   --section      Import into <section> (default: subscription)
##   --security     Use the specified <provider>
##
## Returns 0 if successful, non-zero if an error occurs.
##
function p_cmd_import_key() {
	local provider=$(psub_get_provider)
	local section="subscription"
	
	local lopts="security:,section:"
	local args=$(getopt -o "+" -l "${lopts}" -n "$0" -- "$@")
	local status=$?
	
	if ((status == 0)); then
		eval set -- "${args}"
		
		while [[ "$1" != "--" ]]; do
			case "$1" in
				--security)
					shift
					provider="$1"
					shift
				;;
				--section)
					shift
					section="$1"
					shift
				;;
			esac
		done
		
		shift
	
		if [[ $# -ne 1 ]]; then
			echo "Usage: pulley import_key [options] <key URL>"
			status=2
		fi
	fi
	
	if ((status == 0)); then
		psec_import_key "${section}" "${provider}" "$1"
		status=$?
	fi
	
	return ${status}
}
